<?php

namespace app\admin\controller;

use app\user\model\UserModel;
use api\mall\model\UserAuditModel;
use cmf\controller\BaseController;

class AuditDetailController extends BaseController
{
    public function doAudit()
    {
        if ($this->request->post()) {
            $model = new UserAuditModel();
            $data = $this->request->post();
            if (empty($data['id'])) {
                return $this->fail('无效的记录ID');
            } else {
                // 获取用户信息
                $userModel = new UserModel();
                $user = $userModel->where('id', $data['user_id'])->find();
                // 获取审核信息
                $userAuditModel = new UserAuditModel();
                $userAudit = $userAuditModel->where('id', $data['id'])->find();
                // 判断用户是否存在
                if (empty($user) || empty($userAudit)) {
                    return $this->fail('无效的用户ID');
                }

                $userUpdate = [];
                $auditUpdate = [];
                if ($data['audit_status'] != 0) {
                    // 重新审核
                    $userUpdate['user_nickname'] = $userAudit['before_nickname'];
                    $userUpdate['avatar'] = $userAudit['before_avatar'];

                    $auditUpdate['audit_status'] = 0;
                    $auditUpdate['update_time'] = time();
                }
                else {
                    // 审核
                    if ($data['new_status'] == 1) {
                        if (!empty($userAudit['audit_nickname'])) {
                            $userUpdate['user_nickname'] = $userAudit['audit_nickname'];
                        }
                        if (!empty($userAudit['audit_avatar'])) {
                            $userUpdate['avatar'] = $userAudit['audit_avatar'];
                        }
                    }

                    $auditUpdate['audit_status'] = $data['new_status'];
                    $auditUpdate['update_time'] = time();                    
                }
                
                $userModel->where('id', $user['id'])->update($userUpdate);
                $userAuditModel->where('id', $data['id'])->update($auditUpdate);
            }
            return $this->success(lang('EDIT_SUCCESS'), null, '', 1);
        } else {
            return $this->fail('参数错误');
        }
    }
}
